#include <time.h>
#include <string.h>
#include "shtml.h"
#include <stdarg.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <signal.h>
#include <errno.h>

const int max_proxy=100;
string proxies[max_proxy];
string useragent[6];
int id=0;
static bool STOP=false;
void call_for_exit(int s)
{
   STOP=true;
}
void getProxyList()
{
	string line;
	ifstream myFile("/etc/proxy.txt");
	if(!myFile.good())
	{
		cout << "Error opening file proxy.txt"<<endl;
		return ;
	}
    id=0;
	while(!myFile.eof())
	{
		getline(myFile, line);
		proxies[id]=line;
		id++;
		if (id>=max_proxy) break;
	}
	id--;id--;
	myFile.close();
    cout<<"Get total "<<id<<" proxies"<<endl;
}
void curl_proxy(char * url)
{
    char cmd[300];
    int i=0;
    int a;
    while (i<id)
    {
        a=rand() % 6;
        sprintf(cmd,"curl -A \"%s\" -s -x %s %s >/dev/null",useragent[a].c_str(),proxies[i].c_str(),url);
        cout<<i<<". CURL: "<<cmd<<endl;
        system(cmd);
        //sleep(1);
        i++;
    }

}
void help()
{
    cout<<"visit an url via proxy"<<endl;
    cout<<"v1.0 - by Tran Huu Nam - huunam0@gmail.com"<<endl;
    cout<<"Usage: visit <url> [count]"<<endl;
}
int main(int argc, char** argv)
{
    int iTimes=1;
    if (argc<2)
    {
        help();
        return 1;
    }
    if (argc>2)
    {
        iTimes=atoi(argv[2]);
    }
    useragent[0]=string("Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3");
    useragent[1]=string("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.112 Safari/534.30");
    useragent[2]=string("Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0");
    useragent[3]=string("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:21.0) Gecko/20130331 Firefox/21.0");
    useragent[4]=string("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)");
    useragent[5]=string("Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US)");

    signal(SIGQUIT,call_for_exit);
    signal(SIGKILL,call_for_exit);
    signal(SIGTERM,call_for_exit);

	getProxyList();
    while (iTimes!=0)
    {
        curl_proxy(argv[1]);
        //sleep(10);
        iTimes--;
    }

    return 0;
}
